package com.cimu.structural.proxy.dynamic;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * Title: OrderServiceDynamicProxy
 * Copyright: Copyright (c) 2017
 *
 * @author cgx
 * date 2019年07月21日 13:18
 */
public class OrderServiceDynamicProxy implements InvocationHandler {
    /**
     * 具体的实现类,如OrderServiceImpl
     */
    private Object target;
    public OrderServiceDynamicProxy(Object target) {
        this.target = target;
    }
    public Object bind(){
        Class cls = target.getClass();
        //调用代理类的newProxyInstance方法来实例化实现类
        return Proxy.newProxyInstance(cls.getClassLoader(),cls.getInterfaces(),this);
    }
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Object argObject = args[0];
        beforeMethod(argObject);
        //实际调用的方法
        Object object = method.invoke(target,args);
        afterMethod();
        return object;
    }
    private void beforeMethod(Object obj){
        if(obj instanceof Order){
            Order order = (Order)obj;
            System.out.println("保存之前订单参数进行校验");
        }
    }
    private void afterMethod(){
        System.out.println("保存成功之后做点事情");
    }
}
